package org.geekbang.projects.rest.client;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.geekbang.projects.rest.core.AbstractHttpInvocation;
import org.geekbang.projects.rest.core.HttpRequest;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.Locale;

/**
* post请求处理  
* @author : KangNing Hu
*/
class HttpPostHttpInvocation<T> extends AbstractHttpInvocation {



	private Entity<T> entity;


	public HttpPostHttpInvocation(HttpRequest request , Entity<T> entity) {
		super(request);
		this.entity = entity;
	}

	/**
	 * 处理请求体信息
	 * @param connection
	 */
	@Override
	protected void postProcessor(HttpURLConnection connection) {
		super.postProcessor(connection);
		if (this.entity == null){
			return;
		}
		T entity = this.entity.getEntity();
		//设置语言
		Locale language = this.entity.getLanguage();
		if (language != null) {
			this.put(REQUEST_HEADER_ACCEPT_LANGUAGE,language);
		}
		//设置请求body类型
		this.put(REQUEST_HEADER , this.entity.getMediaType().toString());
		//设置编码
		if (StringUtils.isEmpty(this.entity.getEncoding()) ) {
			this.put(REQUEST_HEADER_ACCEPT_ENCODING, this.entity.getEncoding());
		}
		MediaType mediaType = this.entity.getMediaType();
		//处理json格式数据
		if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)){
			//写请求体
			connection.setDoOutput(true);
			try (OutputStream outputStream = connection.getOutputStream()) {
				outputStream.write(JSONObject.toJSONBytes(entity));
			} catch (IOException e) {
				throw new IllegalStateException(e);
			}
		}

	}

	@Override
	protected String getMethod() {
		return HttpMethod.POST;
	}


}
